<?php

namespace app\beautiful\controller\miniapp\staff\writeoff;

use app\BaseController;

use app\beautiful\model\goods\GoodsWriteOffModel;
use app\beautiful\model\mall\FlashSaleGoodsModel;
use app\beautiful\model\mall\PinTuanGroupModel;
use app\beautiful\model\order\GoodsOrderItemModel;
use app\beautiful\model\order\GoodsOrderModel;
use app\beautiful\model\order\OrderGoodsGroupDetailModel;
use app\beautiful\model\order\OrderGoodsGroupModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\common\model\ShopDetailModel;
use think\facade\Db;
use function GuzzleHttp\Psr7\str;


class WriteOff extends BaseController{

    /*套餐核销页面*/
    public function getSetMealWriteOff(){
        $verify_code = $this->request->param('verify_code');
        if(empty($verify_code)) return $this->error('码无效');
        //第一次核销后，订单变为已完成
        $datas = GoodsOrderModel::with(['item'])->where(['shop_id'=>$this->request->shopId,'verify_code'=>$verify_code,'is_delete'=>0,'is_paid'=>1])->find();
        if(empty($datas))   return $this->error('该订单不存在');

        if(!in_array($datas->status,[2,3,4,8,9,10]))   return $this->error('该订单状态不能核销');

        $datas->append(['order_time','djs_time','youhui','pay_time_format','pay_type_mean']);

        $item = $datas->item;

        $goods_id = $item->goods_id;

        $where = [
            ['is_delete','=',0],
            ['order_id','=',$datas->order_id],
            ['order_item_id','=',$item->order_item_id],
        ];

        //拼团订单
        if($datas->order_type=='pin_tuan'){
            $group_goods = PinTuanGroupModel::with(['pinTuanGoods'=>function($query){
                $query->with(['goods']);
            }])->where(['pin_tuan_group_id'=>$datas->pin_tuan_group_id])
                ->find();
            $group_goods = $group_goods?$group_goods->toArray():$group_goods;
            $goods_type = $group_goods['pinTuanGoods']['goods']['type'];

            //拼团套餐
            if($goods_type==3){
                //拼团套餐
                $goods = OrderGoodsModel::where(['pin_tuan_order_id'=>$datas->pin_tuan_order_id])->find();
                $goods_id =$goods->goods_id;
                $where = [
                    ['is_delete','=',0],
                    ['pin_tuan_order_id','=',$datas->pin_tuan_order_id],
                ];
            }
        }
        //秒杀套餐
        if($datas->order_type=='flash_sale'){
            $flash_sale_goods = FlashSaleGoodsModel::where(['flash_sale_goods_id'=>$goods_id])->find();
            $goods_id = $flash_sale_goods->goods_id;

        }

        //套餐其他信息
        //$goods = OrderGoodsModel::where(['goods_id'=>$item->goods_id,'is_delete'=>0,'order_id'=>$datas->order_id,'order_item_id'=>$item->order_item_id])->json(['use_limit_detail'],true)->find();
        $goods = OrderGoodsModel::where($where)->where(['goods_id'=>$goods_id])->json(['use_limit_detail'],true)->find();

        $goods->order_id = $datas->order_id;
        $goods->goods_name = $datas->item->goods_name;
        $goods->goods_cover_img = $datas->item->goods_cover_img;
        $goods->original_price = $datas->item->goods_original_price	;
        $goods->need_pay = $datas->need_pay;
        //到期时间
        $end_time = goodsEndTime($goods,$datas);
        $goods->remarks = $end_time->remarks;
        $goods->is_effect = $end_time->is_effect;

        //分组与分组详情
//        $goods->group = OrderGoodsGroupModel::with(['orderGoodsGroupDetail'=>function($query){
//            $query->where(['is_delete'=>0])->order(['sort'=>'desc']);
//        }])->where(['order_id'=>$datas->order_id,'order_item_id'=>$item->order_item_id,'is_delete'=>0])
//            ->select()->toArray();
        $group = OrderGoodsGroupModel::with(['orderGoodsGroupDetail'=>function($query){
            $query->where(['is_delete'=>0])->order(['sort'=>'desc']);
        }])->where($where)
            ->select()->toArray();
        foreach ($group as $kk=>$vv){
            $group_detail = $vv['orderGoodsGroupDetail'];
            foreach ($group_detail as $k=>$v) {
                $group_detail[$k]['total_goods_price'] = $v['goods_original_price'] * $v['num'];
            }
            $group[$kk]['orderGoodsGroupDetail'] = $group_detail;
        }
        $goods->group = $group;
        //不是一次性核销的
        $remain_num = $num = 0;
        //是否多次核销
        $is_many_write_off = 0;
        $write_off = [];
//        $group_detail = OrderGoodsGroupDetailModel::where(['order_id'=>$datas->order_id,'is_delete'=>0])->select()->toArray();
        $group_detail = OrderGoodsGroupDetailModel::where($where)->select()->toArray();
        $goods_write_off_model = new GoodsWriteOffModel();
        foreach ($group_detail as $k=>$v){
            if($v['use_condition']!=1) $is_many_write_off = 1;
            $num += $v['num'];
            $remain_num += $v['remain_num'];
            if($v['use_condition']!=1 && $v['num']>2 && $v['remain_num']>0){
                //核销数据
                $hx = GoodsWriteOffModel::where(['order_goods_group_detail_id'=>$v['order_goods_group_detail_id'],'goods_id'=>$v['goods_id']])->order(['add_time'=>'asc'])->select()->toArray();
                $v['is_effect'] = 1;
                //套餐详情有效期
                if($v['end_type']==1 && $hx){
                    $first_time = strtotime($hx[0]['add_time']);
                    if($v['end_time_type'] == 1){
                        $v['start_time'] = date('Y-m-d H:i:s',$datas->pay_time);
                        $v['end_time'] = date("Y-m-d",$first_time + $v['end_time_num'] * 86400)." 23:59:59";
                    }else{
                        $v['start_time'] = date('Y-m-d H:i:s',$datas->pay_time);
                        $v['end_time'] = GetMonth($first_time,$v['end_time_num']);

                    }
                    if(time()<strtotime($v['start_time']) && time()>strtotime($v['end_time'])){
                        $v['is_effect'] = 0;
                    }
                }
                $v['write_off'] = $hx;
                $write_off[] = $v;
            }
        }

        //核销完
        $goods->is_end = $remain_num<1?1:0;
        $goods->write_off_data = $write_off;
        //在有效期内未核销完：部分有效
        if($remain_num>0 && $remain_num!=$num && $end_time->is_effect==1){
            $goods->is_effect = 2;
        }
        //在有效期内从未核销：有效
        //第一次核销时间
        $goods_write_off = $goods_write_off_model->getById(['order_id'=>$datas->order_id,'is_delete'=>0],['add_time'=>'asc'],'add_time');
        $goods->write_off_first_time = $goods_write_off?$goods_write_off['add_time']:null;
        $goods->is_many_write_off = $is_many_write_off;
        $goods->goods_name = $datas->activity_title?$datas->activity_title:$goods->goods_name;
        return $this->success($goods);
    }
    /*实现核销*/
    public function setMealWriteOff(){
        $order_id = $this->request->param('order_id');
        $write_off_data = $this->request->param('write_off_data');
//        $write_off_data[]=[
//            'num'=>1,
//            'order_goods_group_detail_id'=>32
//        ];
        for ($i=0;$i<count($write_off_data);$i++){
            $data[$write_off_data[$i]['order_goods_group_detail_id']] = $write_off_data[$i];
        }
        $datas = GoodsOrderModel::with(['item'])->where(['shop_id'=>$this->request->shopId,'order_id'=>$order_id,'is_delete'=>0,'is_paid'=>1])->find();
        if(empty($datas))   return $this->error('该订单不存在');

        $datas->append(['order_time','djs_time','youhui','pay_time_format','pay_type_mean']);
        $item = $datas->item;
        $goods_id = $item->goods_id;
        //秒杀套餐
        if($datas->order_type=='flash_sale'){
            $flash_sale_goods = FlashSaleGoodsModel::where(['flash_sale_goods_id'=>$item->goods_id])->find();
            $goods_id = $flash_sale_goods->goods_id;

        }
        //秒杀套餐
        if($datas->order_type=='pin_tuan'){
            $where_g = [
                ['is_delete','=',0],
                ['pin_tuan_order_id','=',$datas->pin_tuan_order_id]
            ];
            //核销
            $where_g_d = [
                ['is_delete','=',0],
                ['pin_tuan_order_id','=',$datas->pin_tuan_order_id],
            ];

        }else{
            $where_g = [
                ['is_delete','=',0],
                ['goods_id','=',$goods_id],
                ['order_id','=',$datas->order_id],
                ['order_item_id','=',$item->order_item_id]
            ];
            //核销
            $where_g_d = [
                ['is_delete','=',0],
                ['order_id','=',$datas->order_id],
            ];

        }
        //套餐其他信息
        $goods = OrderGoodsModel::where($where_g)->json(['use_limit_detail'],true)->find();
        //到期时间
        $end_time = goodsEndTime($goods,$datas);
        if($end_time->is_effect<1) return $this->error('该订单不在有效时间内');

        //核销
        $group_detail = OrderGoodsGroupDetailModel::where($where_g_d)->select()->toArray();

        Db::startTrans();

        try{
            foreach ($group_detail as $k=>$v){
                //数据是否存在
                if(isset($data[$v['order_goods_group_detail_id']])){
                    //判断数量是否超出
                    if($data[$v['order_goods_group_detail_id']]['num']>$v['remain_num']){
                        return $this->error($v['goods_name'].'数量超过剩余数量'.$v['remain_num']);
                    }
                    //核销数据
                    $hx = GoodsWriteOffModel::where(['order_id'=>$v['order_id'],'order_item_id'=>$v['order_item_id'],'goods_id'=>$v['goods_id']])->order(['add_time'=>'asc'])->select()->toArray();

                    //判断是否超过套餐详情有效期（0不限期1首次核销后截止日期）
                    if($v['end_type']==1 && $hx){
                        $first_time = $hx[0]['add_time'];
                        if($v['end_time_type'] == 1){//天
                            $v['start_time'] = date('Y-m-d H:i:s',$datas->pay_time);
                            $v['end_time'] = date("Y-m-d",strtotime($first_time) + $v['end_time_num'] * 86400)." 23:59:59";
                        }else{//月
                            $v['start_time'] = date('Y-m-d H:i:s',$datas->pay_time);
                            $v['end_time'] = GetMonth($first_time,$v['end_time_num']);

                        }
                        if(time()<strtotime($v['start_time']) || time()>strtotime($v['end_time'])){
                            return $this->error($v['goods_name'].'已超过截止日期');
                        }
                    }

                    if($v['use_condition']==1){
                        //一次性消费完
                        $num = $v['num'];
                        $remain_num = 0;
                    }else if($v['use_condition']==2){
                        //单次限制使用数量(所剩数小于单次限制数，则不用判断)
                        if($v['once_limit_num']==$v['remain_num'] && $v['once_limit_num']!=$data[$v['order_goods_group_detail_id']]['num']){
                            return $this->error($v['goods_name'].'核销数应该为'.$v['once_limit_num']);
                        }
                        $num = $data[$v['order_goods_group_detail_id']]['num'];
                        //减少剩余量
                        $remain_num = $v['remain_num'] - $data[$v['order_goods_group_detail_id']]['num'];
                        $remain_num = $remain_num<0?0:$remain_num;
                    }else{
                        //根据消费需求选择数量
                        $num = $data[$v['order_goods_group_detail_id']]['num'];
                        //减少剩余量
                        $remain_num = $v['remain_num'] - $data[$v['order_goods_group_detail_id']]['num'];
                        $remain_num = $remain_num<0?0:$remain_num;
                    }

                    //修改剩余量
                    GoodsOrderItemModel::where(['order_id'=>$v['order_id'],'order_item_id'=>$v['order_item_id']])->save(['remain_num'=>$remain_num]);
                    OrderGoodsGroupDetailModel::where(['order_goods_group_detail_id'=>$v['order_goods_group_detail_id']])->save(['remain_num'=>$remain_num]);

                    //添加核销数据
                    $write_off_model = new GoodsWriteOffModel();
                    $write_off_model->shop_id = $this->request->shopId;
                    $write_off_model->member_id = $datas->member_id;
                    $write_off_model->set_meal_id = $item->goods_id;
                    $write_off_model->goods_id = $v['goods_id'];
                    $write_off_model->order_id = $order_id;
                    $write_off_model->order_item_id = $v['order_item_id'];
                    $write_off_model->order_goods_group_detail_id = $v['order_goods_group_detail_id'];
                    $write_off_model->num = $num;
                    $write_off_model->remain_num = $remain_num;
                    $write_off_model->type = 3;
                    $write_off_model->operate_type = 1;
                    $write_off_model->operate_id = $this->request->staffId;
                    $write_off_model->operate_mobile = $this->request->staff->mobile;
                    $write_off_model->operate_name = $this->request->staff->name;
                    $write_off_model->save();

                    //第一次核销修改订单状态为已完成
                    if(!$hx){
                        $update_data['status'] = 8;
                        $update_data['edit_time'] = date('Y-m-d H:i:s');
                        GoodsOrderModel::where(['shop_id'=>$this->request->shopId,'order_id'=>$order_id,'is_delete'=>0,'is_paid'=>1])->save($update_data);
                        //股东分红
                        order_bonus($order_id,0);
                        //地推分红
                        if($datas->p_mid>0){
                            promotion_money($datas->team_activity_id,$order_id,1,2);
                        }

                    }

                }

            }
            //语音播报
            $detail = ShopDetailModel::where(['shop_id'=>$this->request->shopId])->find();
            $voice['msg'] = $item->goods_name.'核销成功';
            $voice['sbx_id'] = $detail->sbx_id;
            sendvoice($voice);
            Db::commit();
            return $this->success('核销成功');
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }

}

